import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [// 静态路由
    {
        path: '/', redirect: '/login',
    },
    {
        path: '/login', name: 'Login', component: () => import('../views/Login.vue'), meta: {
            title: '登录'
        }
    }, {
        path: '/register', name: 'Register', component: () => import('../views/Register.vue'), meta: {
            title: '注册'
        }

    }]

const router = new VueRouter({
    mode: 'history', base: process.env.BASE_URL, routes
})

// 注意：刷新页面会重置路由，导致原来设置的动态路由消失
export const setRoutes = () => {
    // 获取当前的路由对象名称数组
    const routeNames = router.getRoutes().map(item => item.name);
    // 如果manage路由不存在，则添加路由
    if (!routeNames.includes('manage')) {
        // 获取本地存储的菜单数据
        const userStoreMenus = JSON.parse(localStorage.getItem("user"));
        if (userStoreMenus) {
            const storeMenus = userStoreMenus.menus;
            let routesRoot = {
                path: '/',
                name: 'manage',
                component: () => import('../views/Manage.vue'),
                redirect: '/home',
                children: [{
                    path: '/persion', name: 'Persion', component: () => import('../views/Persion.vue'), meta: {
                        title: '个人信息'
                    }
                },]
            }

            storeMenus.forEach(item => {
                if (item.path) {
                    let route = {
                        path: item.path,
                        name: item.name,
                        component: () => import('../views/' + item.pagePath + '.vue'),
                        meta: {
                            title: item.name
                        }
                    }
                    routesRoot.children.push(route);
                } else if (item.children) {
                    item.children.forEach(item => {
                        if (item.path) {
                            let route = {
                                path: item.path,
                                name: item.name,
                                component: () => import('../views/' + item.pagePath + '.vue'),
                                meta: {
                                    title: item.name
                                }
                            }
                            routesRoot.children.push(route);
                        }
                    })
                }
            })

            // 404 页面
            let router404 = {
                path: '*', name: '404', component: () => import('../views/404.vue'),
            }
            // 动态添加路由
            router.addRoute(routesRoot);
            router.addRoute(router404);
        }
    }
}

// 重置路由
export const resetRouter = () => {
    router.matcher = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    })
}


// 刷新页面会重置路由，需要重新设置路由
setRoutes();

export default router

